package com.stars.easyms.base.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.jdbc.JdbcProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;

/**
 * <p>className: ConfigurationPropertiesUtil</p>
 * <p>description: ConfigurationProperties工具类</p>
 *
 * @author guoguifang
 * @date 2019-12-20 16:27
 * @since 1.4.2
 */
public final class ConfigurationPropertiesUtil {

    public static <T> T bind(Class<T> clazz) throws IllegalAccessException, InstantiationException {
        T t = clazz.newInstance();
        bind(t);
        return t;
    }

    public static void bind(Object obj) {
        ConfigurationPropertiesBindingPostProcessor bindingPostProcessor =
                ApplicationContextHolder.getBean(ConfigurationPropertiesBindingPostProcessor.class);
        if (bindingPostProcessor != null) {
            String beanName = getName(JdbcProperties.class);
            bindingPostProcessor.postProcessBeforeInitialization(obj, beanName);
            BeanUtil.registerSingleton((ConfigurableApplicationContext) ApplicationContextHolder.getApplicationContext(), beanName, obj);
        }
    }

    public static String getName(Class<?> type) {
        ConfigurationProperties annotation = AnnotationUtils.findAnnotation(type, ConfigurationProperties.class);
        String prefix = (annotation != null) ? annotation.prefix() : "";
        return (StringUtils.isNotBlank(prefix) ? prefix + "-" + type.getName() : type.getName());
    }

    private ConfigurationPropertiesUtil() {
    }
}